import { DefineComponent, markRaw, reactive, watch, defineComponent } from "vue";
import { injectAppNavigator } from "./AppNavigator";

export const AppNavigatorPage = defineComponent({
  setup() {
    const navigator = injectAppNavigator();
    const state = reactive({
      PageComponent: null as null | DefineComponent
    });
    const utils = {
      reset: async () => {
        const route = navigator.state.route;
        if (!route) return;
        let { path } = route;
        if (path?.charAt(0) === '/') {
          path = path.slice(1);
        }
        const Component = (await import('story/pages/' + path)).default; // 懒加载

        state.PageComponent = markRaw(Component); // 处理成非响应式的
      }
    };

    watch(() => navigator.state.route.path, utils.reset, {immediate: true});

    return () => {
      const { PageComponent } = state;
      return PageComponent ? <PageComponent /> : null;
    }
  }
});